import React from "react";
import { Tag, Space } from "antd";
import { useSelector, useDispatch } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { colseTab, setCurrentMenu } from "../store/reducers/tab";

const CommonTag = () => {
  const { tabList, currentMenu } = useSelector((state) => state.tab);
  const action = useLocation();
  const dispatch = useDispatch();
  const navgiate = useNavigate();
  const handleClose = (item, index) => {
    let length = tabList.length - 1;
    dispatch(colseTab(item));
    if (item.path !== action.pathname) {
      return;
    }
    if (index === length) {
      const currentData = tabList[index - 1];
      dispatch(setCurrentMenu(currentData));
      navgiate(currentData.path);
    } else {
      if (tabList.length > 1) {
        const nextData = tabList[index + 1];
        dispatch(setCurrentMenu(nextData));
        navgiate(nextData.path);
      }
    }
  };
  const handleChange = (tag) => {
    dispatch(setCurrentMenu(tag));
    navgiate(tag.path);
  };
  const setTag = (flag, item, index) => {
    return flag ? (
      <Tag
        closeIcon
        onClose={() => {
          handleClose(item, index);
        }}
        color="#55acee"
        key={item.name}
      >
        {item.label}
      </Tag>
    ) : (
      <Tag
        onClick={() => {
          handleChange(item);
        }}
        key={item.name}
      >
        {item.label}
      </Tag>
    );
  };
  return (
    <Space size={[0, 8]} wrap style={{ padding: "24px 0 0 16px" }}>
      {currentMenu?.name &&
        tabList.map((item, index) =>
          setTag(item.path === currentMenu.path, item, index)
        )}
    </Space>
  );
};
export default CommonTag;
